#include "loop.h"

#define MAX_QUEUE 1000

struct
{
    void (*func) (void *);
    void * param;
} static queue[MAX_QUEUE];
static int queue_front = 0;
static int queue_end = 0;

void loop(void (* initial)(void *), void * param)
{
    post(initial, param);
    while (queue_front != queue_end)
    {
        void (* func)(void *) = queue[queue_front].func;
        if (!func)
        {
            queue_front = 0;
            queue_end = 0;
            break;
        }
        void * param = queue[queue_front].param;
        queue_front = (queue_front + 1) % MAX_QUEUE;
        func(param);
    }
}

int post(void (* func)(void *), void * param)
{
    if (queue_front == (queue_end + 1) % MAX_QUEUE) return 0;
    queue[queue_end].func = func;
    queue[queue_end].param = param;
    queue_end = (queue_end + 1) % MAX_QUEUE;
    return 1;
}
